package cn.walls1717.juc.future;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * thenApply handle方法测试
 *
 * @author walls1717
 * @create 2022/12/09 15:44
 **/
@Slf4j
public class CompletableFutureApi2Demo {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        /*
         * thenApply遇到异常会直接终端，跳转到异常处理的方法。
         * handle遇到异常不会停止，会接着执行下面的handle操作。
         */
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("step 1");
            return 1;
        }, executor).handle((v, e) -> {
            int i = 1/0;
            log.info("step 2");
            return v + 2;
        }).handle((v, e) -> {
            log.info("step 3");
            return v + 3;
        }).whenComplete((v, e) -> {
            if (e == null) {
                log.info("result is {}", v);
            } else {
                log.info(e.getCause() + " | " + e.getMessage());
            }
        });

        log.info(Thread.currentThread().getName() + "线程执行其它业务");

        executor.shutdown();

    }
}
